<template>
	<!-- 定期排查新增页面 -->
	<view class="workApply-container" :style="{ height: `${windowHeight}px` }">
		<uni-popup ref="message" type="message">
			<uni-popup-message type="warn" :message="messageText" :duration="2000"></uni-popup-message>
		</uni-popup>
		<!-- 基础表单校验 -->
		<uni-forms ref="valiForm" :rules="rules" :modelValue="valiFormData" border>
			<uni-forms-item label="任务编号：" name="taskNumber">
				<uni-easyinput v-model="valiFormData.taskNumber" disabled placeholder="请输入" :inputBorder="false" />
			</uni-forms-item>
			<uni-forms-item label="所属检查计划：" required name="planId">
				<custom-tree-select :listData="checkPlanOption" @selectChange="handleChange" :search="true"
					dataLabel="planCategory" dataValue="id" v-model="valiFormData.planId" />
				<!-- <uni-data-select :localdata="checkPlanOption" @change="checkPlanChange" v-model="valiFormData.planId" /> -->
			</uni-forms-item>
			<uni-forms-item label="检查任务名称：" required name="taskName">
				<uni-easyinput v-model="valiFormData.taskName" placeholder="请输入" :inputBorder="false" />
			</uni-forms-item>
			<!-- 上面选择检查计划回写上来的 -->
			<uni-forms-item label="检查层级：" required name="taskLevel">
				<template v-if="valiFormData.taskLevel == 1">公司级</template>
				<template v-else-if="valiFormData.taskLevel == 2">部门级</template>
				<template v-else-if="valiFormData.taskLevel == 3">班组级</template>
			</uni-forms-item>
			<uni-forms-item label="检查时间：" required name="taskTime">
				<uni-datetime-picker type="date" :start="startDate" :end="endDate" :clear-icon="false"
					v-model="valiFormData.taskTime" :disabledDate="disabledDate" />
			</uni-forms-item>
			<!-- 上面选择检查计划回写上来的 -->
			<uni-forms-item label="检查执行人：" required name="examineExecutorId">
				<!-- <text> {{valiFormData.examineExecutorName}}</text> -->
				<uni-data-select :localdata="executorList" disabled v-model="valiFormData.examineExecutorId" />
			</uni-forms-item>
			<!-- 多选 -->
			<uni-forms-item label="检查参与人：" required name="examineParticipantIds	">
				<custom-tree-select :listData="allUsers" dataLabel="nickName" dataValue="userId" :search="true"
					@selectChange="deptChange" :mutiple="true" v-model="valiFormData.examineParticipantIds" />

				</custom-tree-select>
			</uni-forms-item>
			<!-- 上面选择检查计划回写上来的 -->
			<uni-forms-item label="被检查单位：" required name="passReviewUnitId">

				<custom-tree-select :listData="treeData" dataLabel="label" dataValue="id" :search="true"
					v-model="valiFormData.passReviewUnitId" />

				</custom-tree-select>

			</uni-forms-item>

			<uni-forms-item label="外部人员："  name="outPerson">
				<uni-easyinput v-model="valiFormData.outPerson" placeholder="请输入" :inputBorder="false" />
			</uni-forms-item>
			<uni-forms-item label="检查表内容：" required>
				<button type="primary" size="mini" @click="manualBtn">手工选择</button>
				<button size="mini" @click="getStand">获取上次检查标准</button>
			</uni-forms-item>
		</uni-forms>
		<uni-table ref="table" :loading="loading" border stripe type="selection" emptyText="暂无更多数据"
			@selection-change="selectionChange">
			<uni-tr>
				<uni-th width="50" align="center">序号</uni-th>
				<uni-th width="100" align="center">检查范围</uni-th>
				<uni-th width="100" align="center">检查标准</uni-th>
				<uni-th width="100" align="center">操作</uni-th>
			</uni-tr>
			<uni-tr v-for="(item, index) in tableData" :key="index">
				<uni-td>{{ index +1 }}</uni-td>
				<uni-td>
					<view class="name">{{ item.inspectionScopeName }}</view>
				</uni-td>
				<uni-td align="center">{{ item.inspectionStandard }}</uni-td>
				<uni-td>
					<view class="uni-group">
						<button class="uni-button" v-if="item.inspectionScopeName !== '其他'" size="mini" type="warn"
							@click="deleteTrouble(item)">删除</button>
					</view>
				</uni-td>
			</uni-tr>
		</uni-table>


		<button type="primary" @click="submit('valiForm')" class="submit-btn">
			确认
		</button>

		<templtae v-if="manualVisible">
			<CheckPlan ref="planChild" @manualCheck="manualCheckBack"></CheckPlan>
		</templtae>
	</view>
</template>

<script>
	import widowHeightMixins from "@/mixins/widowHeightMixins.js";
	import ManualSelect from "./modal/manualSelect.vue"
	import CheckPlan from "./modal/checkPlan.vue"
	import {
		getNowTime
	} from "@/utils/nowTime.js"
	import {
		sendRegular,
		addRegular,
		listFrontRegular
	} from "@/api/hiddenTrouble/periodShoot.js";
	import {
		listCheckPlan,
		getCheckPlan

	} from "@/api/hiddenTrouble/checkPlan.js"
	import {
		getInfo,
		allUser,
		listUser
	} from "@/api/system/user.js"
	import {
		deptTreeSelect
	} from "@/api/system/user";
	import {
		mapGetters
	} from "vuex"

	import dayjs from 'dayjs';
	export default {
		mixins: [widowHeightMixins],
		components: {
			ManualSelect,
			CheckPlan
		},
		onLoad(e) {
			// console.log(e, "e--");
			const eventChannel = this.getOpenerEventChannel()
			eventChannel.on('acceptDataFromOpenedPage', (data) => {
				this.queryForm.pageStatus = data.pageStatus
				// console.log("接受---", data)
				this.operateStatus = data.operateStatus
				this.checkId = data.checkId
				this.taskStatus = data.taskStatus
				if (data.operateStatus == 1) {
					this.handleopen(data.totalObj.summaryOne)
				}

			});
			// 动态设置标题
			uni.setNavigationBarTitle({
				title: `定期排查流程--发起`,
			});
		},
		data() {
			return {
				//提示信息
				messageText: "",
				allUsers: [],
				//选中ID
				checkId: null,
				//操作状态
				operateStatus: null,
				//开始日期
				startDate: null,
				//结束日期
				endDate: null,
				//上传参数对象
				queryForm: {},
				//检查时间校验
				disabledDate: [],

				//手工选择弹窗
				manualVisible: false,
				//被检查单位的数据
				treeData: [],
				//当前任务状态
				taskStatus: "",
				// 校验表单数据
				valiFormData: {},
				taskLevelOption: [],
				//所属检查计划的option
				checkPlanOption: [],
				localRes: {},
				//检查表内容
				tableData: [{
						id: "999",
						inspectionScopeName: "其他",
						inspectionCategoryName: "其他",
						inspectionStandard: "其他",
					},

				],
				// 每页数据量
				pageSize: 10,
				// 当前页
				pageCurrent: 1,
				// 数据总量
				total: 0,
				loading: false,
				//检查执行人
				executorList: [],
				// 动火人下拉框
				peopleOption: [{
						value: 0,
						text: "人员1"
					},
					{
						value: 1,
						text: "人员2"
					},
					{
						value: 2,
						text: "人员3"
					},
				],

				// 校验规则
				rules: {
					dept: {
						rules: [{
							required: true,
							errorMessage: "姓名不能为空",
						}, ],
					},
					name: {
						rules: [{
							required: true,
							errorMessage: "姓名不能为空",
						}, ],
					},
					age: {
						rules: [{
								required: true,
								errorMessage: "年龄不能为空",
							},
							{
								format: "number",
								errorMessage: "年龄只能输入数字",
							},
						],
					},
				},
			};
		},
		methods: {
			/** 删除 */
			deleteTrouble(row) {
				// console.log("row===", row);
				var index = this.tableData.indexOf(row);
				if (index !== -1) {
					this.tableData.splice(index, 1);
				}
			},
			//7天的时间
			checkDate() {
				let oneDate = Date.now() - 6 * 24 * 60 * 60 * 1000;
				let twoDate = Date.now()
				this.startDate = dayjs(oneDate).format('YYYY-MM-DD')
				this.endDate = dayjs(twoDate).format('YYYY-MM-DD')
			},


			//计划的change事件
			handleChange(val) {
				if (val.length >= 1) {
					this.$set(this.valiFormData, 'taskLevel', val[0].planLevel)
				} else {
					this.$set(this.valiFormData, 'taskLevel', "")
				}

			},
			//处理详情接口数据回写上面
			handleopen(data) {

				this.valiFormData = data;

				this.valiFormData.approverIds = data.approverIds?.map((item) => {
					return {
						approverId: item,
					};
				});
				this.valiFormData.planId = [data.planId]
				this.valiFormData.passReviewUnitId = [data.passReviewUnitId]
				this.valiFormData.planUserName = data.examineExecutorName;
				this.valiFormData.pageStatus = this.queryForm.pageStatus
				this.userList = [
					...data.participantVo,
					...data.approverVo,
				]; //参与人和审批人结合到一起

				let arr = data.examineParticipantIds.split(",");


				this.valiFormData.examineParticipantIds = arr?.map((item) => {
					return Number(item);
				});

				this.tableData = data.hiddentroubleInspectionTables;
			},
			/** 被检查部门部门下拉树结构 */
			async getDeptTree() {
				const response = await deptTreeSelect();
				this.treeData = response.data;
			},
			deptChange() {},
			// 手工选择按钮
			manualBtn() {
				this.manualVisible = true
				this.$nextTick(() => {

					this.$refs["planChild"].showDrawer()
					// this.$refs["manualChild"].changeShow()
				})
			},
			//获取用户的option
			async getUserOption() {
				let res = await listUser()
				console.log("获取用户", res)
			},
			//获取当前时间
			getTime() {
				let timer = getNowTime(0)
				this.valiFormData.taskNumber = `DQ${timer}`
			},
			/** 获取上次检查标准 */
			async getStand() {

				if (this.valiFormData.planId == "" || this.valiFormData.planId == null) {
					this.messageText = `请先选择检查计划`
					this.$refs.message.open()
					return
				}
				let query = {
					planId: this.valiFormData.planId.join(","),
				};
				let res = await listFrontRegular(query);
				let arr = res.data || [];

				let arr1 = [...arr, ...this.tableData];
				let nowArr = this.getUniqueUsersById(arr1)
			},
			//手工选择返回
			manualCheckBack(val) {
				// console.log("返回的", val)
				let arr = [...val, ...this.tableData]
				let isHave = arr.some((item) => item.id == "999");
				// console.log("是否有", isHave);
				if (!isHave) {
					arr.push({
						id: "999",
						inspectionScopeName: "其他",
						inspectionCategoryName: "其他",
						inspectionStandard: "其他",
					});
				}
				this.tableData = this.getUniqueUsersById(arr)


			},
			//数组对象去重
			getUniqueUsersById(users) {
				const seenIds = new Set();
				return users.filter(user => {
					if (!seenIds.has(user.id)) {
						seenIds.add(user.id);
						return true;
					}
					return false;
				});
			},



			//获取所属检查计划数据
			async getCheckPlans() {
				this.localRes = uni.getStorageSync("userInfo")
				// console.log("当前登录人", localRes)`
				let query = {
					deptId: this.localRes.companyAccount,
					noPage: 1
				}
				let res = await listCheckPlan(query);
				this.checkPlanOption = res.rows
				// this.checkPlanOption = res.rows.map((item) => {
				// 	return {
				// 		value: item.id,
				// 		text: item.planCategory
				// 	}
				// })
			},
			// 切换检查计划
			async checkPlanChange(val) {
				let res = await getCheckPlan(val);
				this.$set(this.valiFormData, 'taskLevel', res.data.planLevel)

			},
			/** 获取当前登陆人信息 */
			async getUserInfo() {
				let res = await getInfo();
				// console.log("用户", res);
				this.executorList = [{
					value: res.user.userId,
					text: res.user.nickName,
				}, ];
				this.valiFormData.examineExecutorId = res.user.userId;
			},
			// 多选
			selectionChange(e) {
				console.log(e.detail.index)
				// this.selectedIndexs = e.detail.index
			},
			//获取检查参与人
			async getParticipantOption() {
				let query = {
					companyAccount: this.localRes.companyAccount,
				}
				let res = await allUser(query)
				this.allUsers = res.rows

			},
			submit(ref) {
				this.$refs[ref]
					.validate()
					.then(async (res) => {

						res.standardIds = this.tableData.map((item) => {
							return item.id;
						});
						res.examineParticipantIds =
							this.valiFormData.examineParticipantIds.join(",");
						res.planId =
							this.valiFormData.planId.join(",");

						console.log("success", res);
						res.pageStatus = this.queryForm.pageStatus
						res.passReviewUnitId = res.passReviewUnitId.toString()
						let query = res
						if (this.operateStatus == 1) {
							uni.showLoading({
								title: "提交中"
							})
							let params = {
								pageStatus: this.queryForm.pageStatus,
								id: this.checkId,
							}

							let res = await sendRegular(params);
							uni.hideLoading()
							uni.navigateTo({
								url: "/pages/trouble/index"
							})
						} else if (this.operateStatus == 2) {
							uni.showLoading({
								title: "提交中"
							})
							const response = await addRegular(query);
							uni.hideLoading()
							uni.navigateTo({
								url: "/pages/trouble/index"
							})


						}

					})
					.catch((err) => {
						console.log("err", err);
					});
			},
		},
		mounted() {
			this.getCheckPlans()
			this.getUserInfo()
			// this.getUserOption()
			this.getTime()
			this.getDeptTree()
			this.checkDate()
			this.getParticipantOption()
		},
		computed: {

		}
	};
</script>

<style lang="scss" scoped>
	.workApply-container {
		padding: 20rpx;
		background-color: #fff;
		overflow-y: auto;

		::v-deep {
			.uni-forms-item--border {
				border-top: 0 solid #000;
				border-bottom: 2rpx solid #e8eaec;
			}

			.uni-forms-item__label {
				width: 40% !important;
			}

			.submit-btn {
				margin-top: 30rpx;
				background: #137ee9;
				border-radius: 10rpx;
			}
		}
	}
</style>